#!/usr/bin/env bash
set -euo pipefail

# mongosh installation script
# Installs mongosh from a local tgz file
# - Extracts mongosh binary from tgz archive
# - Installs to /opt/RadMedical/product/tool/mongodb/bin/mongosh
# - Creates symlink to /usr/local/bin/mongosh for global access

MONGODB_BASE_DIR="/opt/RadMedical/product/tool/mongodb"
MONGODB_BIN_DIR="${MONGODB_BASE_DIR}/bin"
MONGODB_USER="mongod"
MONGODB_GROUP="mongod"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Allow specifying a local mongosh tgz path explicitly (takes precedence)
MONGOSH_TGZ_PATH="${MONGOSH_TGZ_PATH:-}"

ensure_root() {
	if [[ "${EUID}" -ne 0 ]]; then
		echo "Please run as root."
		exit 1
	fi
}

ensure_directories() {
	# Create bin directory if it doesn't exist
	if [[ ! -d "${MONGODB_BIN_DIR}" ]]; then
		echo "Creating MongoDB bin directory: ${MONGODB_BIN_DIR}"
		mkdir -p "${MONGODB_BIN_DIR}"
		chown "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_BIN_DIR}" || true
		chmod 0755 "${MONGODB_BIN_DIR}"
	fi
}

main() {
	ensure_root
	
	# Check if mongosh is already available
	if command -v mongosh >/dev/null 2>&1 && [[ -f "${MONGODB_BIN_DIR}/mongosh" ]]; then
		echo "mongosh is already installed at ${MONGODB_BIN_DIR}/mongosh"
		local version
		version="$("${MONGODB_BIN_DIR}/mongosh" --version 2>/dev/null || echo "unknown")"
		echo "Current version: ${version}"
		exit 0
	fi

	ensure_directories

	local tmpdir
	tmpdir="$(mktemp -d)"
	trap 'rm -rf "${tmpdir}"' EXIT

	local tgz_src=""
	# Priority 1: explicit local path via env
	if [[ -n "${MONGOSH_TGZ_PATH}" && -f "${MONGOSH_TGZ_PATH}" ]]; then
		tgz_src="${MONGOSH_TGZ_PATH}"
		echo "Using local mongosh tgz (MONGOSH_TGZ_PATH): ${tgz_src}"
	# Priority 2: same directory as this script (offline install)
	elif [[ -f "${SCRIPT_DIR}/mongosh-2.5.9-linux-x64.tgz" ]]; then
		tgz_src="${SCRIPT_DIR}/mongosh-2.5.9-linux-x64.tgz"
		echo "Using local mongosh tgz next to script: ${tgz_src}"
	# Priority 3: try to find any mongosh-*.tgz in script directory
	else
		local found_tgz
		found_tgz="$(find "${SCRIPT_DIR}" -maxdepth 1 -name "mongosh-*.tgz" -type f 2>/dev/null | head -n 1)"
		if [[ -n "${found_tgz}" && -f "${found_tgz}" ]]; then
			tgz_src="${found_tgz}"
			echo "Using found mongosh tgz: ${tgz_src}"
		fi
	fi

	if [[ -z "${tgz_src}" || ! -f "${tgz_src}" ]]; then
		echo "Error: mongosh tgz file not found."
		echo "  To install mongosh, place mongosh-*.tgz in ${SCRIPT_DIR}/"
		echo "  or set MONGOSH_TGZ_PATH environment variable."
		echo ""
		echo "Example:"
		echo "  export MONGOSH_TGZ_PATH=\"/path/to/mongosh-2.5.9-linux-x64.tgz\""
		echo "  sudo ${0}"
		exit 1
	fi

	echo "Installing mongosh from ${tgz_src}..."
	
	# Extract tgz
	tar -xzf "${tgz_src}" -C "${tmpdir}" || {
		echo "Error: Failed to extract ${tgz_src}"
		exit 1
	}

	# Find mongosh binary in extracted directory
	local mongosh_bin
	mongosh_bin="$(find "${tmpdir}" -name "mongosh" -type f -executable 2>/dev/null | head -n 1)"
	
	if [[ -z "${mongosh_bin}" || ! -f "${mongosh_bin}" ]]; then
		echo "Error: mongosh binary not found in extracted archive"
		exit 1
	fi

	# Copy mongosh to our bin directory
	cp -f "${mongosh_bin}" "${MONGODB_BIN_DIR}/mongosh" || {
		echo "Error: Failed to copy mongosh to ${MONGODB_BIN_DIR}"
		exit 1
	}

	# Set permissions
	chown "${MONGODB_USER}:${MONGODB_GROUP}" "${MONGODB_BIN_DIR}/mongosh"
	chmod 0755 "${MONGODB_BIN_DIR}/mongosh"

	# Create symlink to /usr/local/bin for global access (optional)
	if [[ -d "/usr/local/bin" ]]; then
		ln -sf "${MONGODB_BIN_DIR}/mongosh" "/usr/local/bin/mongosh" || true
		echo "Created symlink: /usr/local/bin/mongosh -> ${MONGODB_BIN_DIR}/mongosh"
	fi

	echo "mongosh installed successfully at ${MONGODB_BIN_DIR}/mongosh"
	
	# Verify installation
	if [[ -x "${MONGODB_BIN_DIR}/mongosh" ]]; then
		local version
		version="$("${MONGODB_BIN_DIR}/mongosh" --version 2>/dev/null || echo "unknown")"
		echo "mongosh version: ${version}"
		echo ""
		echo "You can now use mongosh:"
		echo "  ${MONGODB_BIN_DIR}/mongosh"
		echo "  or"
		echo "  mongosh  (if /usr/local/bin is in your PATH)"
	fi
}

main "$@"

